//
//  ZYXDownLoadVC.m
//  RuiBeiKang
//
//  Created by iOS开发1 on 2019/1/8.
//  Copyright © 2019年 JW. All rights reserved.
//

#import "ZYXDownLoadVC.h"
#import "ZYXClassNameHeaderView.h"
#import "ZYXDownLoadCell.h"
#import "ZYXClassNameModel.h"
#import "ZYXDownSuccessVC.h"

#import "YCDownloadManager.h"
#import "Reachability.h"
#import "ZYXLayOutView.h"
@interface ZYXDownLoadVC ()<ZYXClassNameHeaderDelegate,ZYXDownLoadCellDelegate>
///数据源
@property (strong, nonatomic) NSMutableArray *dataMArr;

@property (strong, nonatomic) NSIndexPath *indexPath;
@property (weak, nonatomic) IBOutlet UIButton *allSelectBtn;
@property (strong,nonatomic) ZYXLayOutView *alterView;
///是否全选
@property (assign,nonatomic) BOOL isAllSelect;
@end

@implementation ZYXDownLoadVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"视频下载";
    self.isLoading = YES;
}

-(void)setupViews{
    self.isAllSelect = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"ZYXDownLoadCell" bundle:nil] forCellReuseIdentifier:@"ZYXDownLoadCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZYXClassNameHeaderView" bundle:nil] forHeaderFooterViewReuseIdentifier:@"ZYXClassNameHeaderView"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.estimatedRowHeight = aufont(30);
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-NavigationBar_Height-HEIGHT(48)-HomeIndicator_Height);
    
}
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    if (self.dataMArr.count > 0) {
        return NO;
    }
    return YES;
}
-(void)loadData{
//    ZYXClassNameDerailModel *model0_0 = [[ZYXClassNameDerailModel alloc]initWitTitle:@"1-1 什么是类和对象"andVideo_url:@"http://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_1920_18MG.mp4" andVid:@"100000" isSelect:NO];
//    ZYXClassNameDerailModel *model0_1 = [[ZYXClassNameDerailModel alloc]initWitTitle:@"1-2 Java中的static使用之静态初始...Java中的static使用之静态初始...Java中的static使用之静态初始..." andVideo_url:@"http://oss.onezen.cc/video/test-download-xs-max.mp4" andVid:@"100001" isSelect:NO];
//    ZYXClassNameDerailModel *model1_0 = [[ZYXClassNameDerailModel alloc]initWitTitle:@"2-1 什么是类和对象" andVideo_url:@"http://api.onezen.cc/video/301/1.mp4" andVid:@"100002" isSelect:NO];
//    ZYXClassNameDerailModel *model1_1 = [[ZYXClassNameDerailModel alloc]initWitTitle:@"2-2 Java中的static使用之静态初始.." andVideo_url:@"http://rajy.oss-cn-hangzhou.aliyuncs.com/vke/%E4%B8%83%E5%B9%B4%E7%BA%A7%E4%B8%8B%E5%86%8C%E5%86%8C%E5%A4%9A%E5%AA%92%E4%BD%93DVD%E5%86%85%E5%AE%B9/UNIT6%20Our%20Local%20Area%20TOPIC%201%20There%20is%20a%20study%20next%20to%20my%20bedroom%20SectionD.mp4" andVid:@"100003" isSelect:NO];
//    ZYXClassNameDerailModel *model1_2 = [[ZYXClassNameDerailModel alloc]initWitTitle:@"2-3 如何定义Java中的类" andVideo_url:@"https://vd1.bdstatic.com/mda-hiqmm8s10vww26sx/mda-hiqmm8s10vww26sx.mp4" andVid:@"100004" isSelect:NO];
//    ZYXClassNameDerailModel *model2_0 = [[ZYXClassNameDerailModel alloc]initWitTitle:@"3-1 什么是类和对象" andVideo_url:@"https://vd1.bdstatic.com/mda-hez17qvhyauh9ybf/mda-hez17qvhyauh9ybf.mp4" andVid:@"100005" isSelect:NO];
//    ZYXClassNameDerailModel *model2_1 = [[ZYXClassNameDerailModel alloc]initWitTitle:@"3-2 Java中的static使用之静态初始" andVideo_url:@"https://vd1.bdstatic.com/mda-hiwgyhhpzdscwkyu/mda-hiwgyhhpzdscwkyu.mp4" andVid:@"100006" isSelect:NO];
//    ZYXClassNameDerailModel *model2_2 = [[ZYXClassNameDerailModel alloc]initWitTitle:@"3-3 如何定义Java中的类" andVideo_url:@"http://vd1.bdstatic.com/mda-hifgbu4tm1a1qzeu/mda-hifgbu4tm1a1qzeu.mp4" andVid:@"100007" isSelect:NO];
//    ZYXClassNameModel *model0 = [[ZYXClassNameModel alloc]initWitTitle:@"第一章 基本工具" andNSArry:@[model0_0,model0_1] isMore:NO];
//    ZYXClassNameModel *model1 = [[ZYXClassNameModel alloc]initWitTitle:@"第二章 Java中的封装" andNSArry:@[model1_0,model1_1,model1_2] isMore:NO];
//    ZYXClassNameModel *model2 = [[ZYXClassNameModel alloc]initWitTitle:@"第三章 Java中的继承第三章 Java中的继承第三章 Java中的继承" andNSArry:@[model2_0,model2_1,model2_2] isMore:NO];
//    self.dataMArr = [NSMutableArray arrayWithObjects:model0,model1,model2, nil];
    
    
    
    [NetWork POSTWithUrlString:kInterfaceAllUrl(PATH_FenleiThree) parmas:@{@"zid":self.zid,@"user_id":UID} successBloock:^(NSDictionary *responseObject) {
        NSLog(@"responseObject =%@",responseObject);
        if ([responseObject[@"code"] isEqualToNumber:@200]) {
            
            NSArray *modelArr = [ZYXClassNameModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            self.dataMArr = [NSMutableArray arrayWithArray:modelArr];
            NSInteger isYes = 0;
            if (self.dataMArr.count>0) {
                for (ZYXClassNameModel *model in self.dataMArr) {
               
                        model.isTop = NO;
                }
            }
     
            [self.tableView reloadData];
        }else{
            [JKToast showWithText:responseObject[@"message"]];
        }
        
    } failureBlock:^(NSError *error) {
        
    }];
    [self.tableView reloadData];
}
#pragma mark UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataMArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    ZYXClassNameModel *model = self.dataMArr[section];
    if (model.isTop) {
       return model.res.count;
    }else{
        return 0;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ZYXClassNameModel *model = self.dataMArr[indexPath.section];
       ZYXClassNameDerailModel *detModel= model.res[indexPath.row];;
    ZYXDownLoadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZYXDownLoadCell"];
    cell.indexPath = indexPath;
    cell.model = detModel;
    cell.delegate = self;
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    ZYXClassNameModel *model = self.dataMArr[section];
    ZYXClassNameHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ZYXClassNameHeaderView"];
    view.delegate = self;
    view.model = model;
    view.indexPath = section;
    return view;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
    view.backgroundColor = RGB(230, 230, 230);
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return aufont(40);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    ZYXClassNameModel *model = self.dataMArr[section];
    if (model.isTop) {
        return 1;
    }else{
        return CGFLOAT_MIN;
    }
    
}

#pragma mark ZYXClassNameHeaderView
-(void)didClickTopBtn:(NSInteger)tag andView:(ZYXClassNameHeaderView *)view{
    ZYXClassNameModel *model = self.dataMArr[tag];
    model.isTop = !model.isTop;
    [self.tableView reloadData];
    
}
#pragma mark ZYXDownLoadCellDelegate
-(void)didClickSelectBtn:(NSIndexPath *)tag{
    ZYXClassNameModel *model = self.dataMArr[tag.section];
    ZYXClassNameDerailModel *detModel= model.res[tag.row];
    detModel.isSelect = !detModel.isSelect;
    
    self.isAllSelect = [self justIsAllSelect];
    if (self.isAllSelect) {
        [self.allSelectBtn setTitle:@"取消全选" forState:UIControlStateNormal];
    }else{
        [self.allSelectBtn setTitle:@"全选" forState:UIControlStateNormal];
    }
    [self.tableView reloadData];
    
    
}
#pragma mark 判断是否全选
-(BOOL)justIsAllSelect{
    
    BOOL isAll = NO;
    for (ZYXClassNameModel *modeOne in self.dataMArr) {
        
        for(ZYXClassNameDerailModel *model in modeOne.res ){
            if (model.isSelect) {
                
                isAll = YES;
                
            }else{
                
                isAll = NO;
                break;
            }
            
        }
        if (!isAll) {
            break;
        }
    }
    return isAll;
}
#pragma mark 全选
- (IBAction)clickSelectALL:(UIButton *)sender {
    
    for (ZYXClassNameModel *modeOne in self.dataMArr) {
        for(ZYXClassNameDerailModel *model in modeOne.res ){
            model.isSelect = !self.isAllSelect;
            
        }
    }
    if (self.isAllSelect) {
        [self.allSelectBtn setTitle:@"全选" forState:UIControlStateNormal];
    }else{
        [self.allSelectBtn setTitle:@"取消全选" forState:UIControlStateNormal];
    }
    self.isAllSelect = !self.isAllSelect;
    [self.tableView reloadData];
    
}
#pragma mark 判断有无选中
-(BOOL)justIsSelect{
    
    BOOL iselect = NO;
    for (ZYXClassNameModel *modeOne in self.dataMArr) {
        
        for(ZYXClassNameDerailModel *model in modeOne.res ){
            if (model.isSelect) {
                
                iselect  = YES;
                break;
                
            }else{
                iselect  = NO;
            }
            
        }
        if (iselect) {
            break;
        }
    }
    return iselect;
    
}
#pragma mark 下载
- (IBAction)clickDownLoad:(UIButton *)sender {
    
//    [self internetStatus];
//    NSLog(@"当前状态 =%@",[self internetStatus]);
    ///添加下载任务
    ///判断有无选中的任务
    if ([self justIsSelect]) {
        NSLog(@"点击确认下载");
        NSString *str = [self internetStatus];
        
        if ([str isEqualToString:@"当前无网路连接"]) {
            [JKToast showWithText:@"当前无网路连接,请查看设置"];
            return;
        }else if ([str isEqualToString:@"蜂窝数据"]) {
            self.alterView.hidden = NO;
        }else{
            for (ZYXClassNameModel *modeOne in self.dataMArr) {
                for(ZYXClassNameDerailModel *model in modeOne.res ){
                    if (model.isSelect) {
                        YCDownloadItem *item = nil;
                        if (model.uid) {
                            item = [YCDownloadManager itemWithFileId:model.uid];
                        }else if (model.video_url){
                            item = [YCDownloadManager itemsWithDownloadUrl:model.video_url].firstObject;
                        }
                        if (!item) {
                            item = [YCDownloadItem itemWithUrl:model.video_url fileId:model.uid];
                            item.extraData = [ZYXClassNameDerailModel dateWithInfoModel:model];
                            item.enableSpeed = true;
                            [YCDownloadManager startDownloadWithItem:item];
                        }
                    }
                    
                }
            }
            ZYXDownSuccessVC *vc = [[ZYXDownSuccessVC alloc]init];
            vc.typeStr = @"down";
            [self.navigationController pushViewController:vc animated:YES];
        }
        
       
    }else{
        [JKToast showWithText:@"您还没有选中任务，请选中后下载"];
    }
 
}

-(void)clcikSureBtn{
    self.alterView.hidden = YES;
    for (ZYXClassNameModel *modeOne in self.dataMArr) {
        for(ZYXClassNameDerailModel *model in modeOne.res ){
            if (model.isSelect) {
                YCDownloadItem *item = nil;
                if (model.uid) {
                    item = [YCDownloadManager itemWithFileId:model.uid];
                }else if (model.video_url){
                    item = [YCDownloadManager itemsWithDownloadUrl:model.video_url].firstObject;
                }
                if (!item) {
                    item = [YCDownloadItem itemWithUrl:model.video_url fileId:model.uid];
                    item.extraData = [ZYXClassNameDerailModel dateWithInfoModel:model];
                    item.enableSpeed = true;
                    [YCDownloadManager startDownloadWithItem:item];
                }
            }
            
        }
    }
    ZYXDownSuccessVC *vc = [[ZYXDownSuccessVC alloc]init];
    vc.typeStr = @"down";
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark 懒加载
- (NSMutableArray *)dataMArr{
    if (!_dataMArr) {
        _dataMArr = [NSMutableArray array];
        
    }
    return _dataMArr;
}

-(ZYXLayOutView *)alterView{
    if (!_alterView) {
        _alterView = [[NSBundle mainBundle] loadNibNamed:@"ZYXLayOutView" owner:nil options:nil].lastObject;
        _alterView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        _alterView.titleLabel.text = @"状态提示";
        _alterView.contentLabel.text = @"您要用流量下载视频吗？";
        [_alterView.sureBtn addTarget:self action:@selector(clcikSureBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _alterView;
}
#pragma mark 判断网络状态
-(NSString *)internetStatus {
    
    Reachability *reachability   = [Reachability reachabilityWithHostName:@"www.apple.com"];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    NSString *net = @"WIFI";
    switch (internetStatus) {
        case ReachableViaWiFi:
            net = @"WIFI";
            break;
            
        case ReachableViaWWAN:
            net = @"蜂窝数据";
            //net = [self getNetType ];   //判断具体类型
            break;
            
        case NotReachable:
            net = @"当前无网路连接";
            
        default:
            break;
    }
    
    return net;
}
@end
